package com.hk.modules.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hk.common.constant.Constants;
import com.hk.common.query.QueryGenerator;
import com.hk.common.redis.Redis;
import com.hk.common.shiro.token.JwtTokenUtil;
import com.hk.common.utils.DateUtils;
import com.hk.common.utils.ResponseUtils;
import com.hk.common.utils.StringUtils;
import com.hk.modules.user.pojo.UserPojo;
import com.hk.modules.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuiyv
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;
    private final JwtTokenUtil jwtTokenUtil;
    private final Redis redis;

    public UserController(UserService userService, JwtTokenUtil jwtTokenUtil, Redis redis) {
        this.userService = userService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.redis = redis;
    }

    @GetMapping("/list")
    public ResponseEntity list(UserPojo userPojo, HttpServletRequest request){
        QueryWrapper<UserPojo> queryWrapper = QueryGenerator.initQueryWrapper(userPojo, request.getParameterMap());
        return ResponseUtils.tryReturn("查询用户信息异常",()->userService.list(queryWrapper));
    }


    @PutMapping("")
    public ResponseEntity addUser(@RequestBody UserPojo p){
        return ResponseUtils.tryReturn("新增用户异常",()->userService.saveUserAndRole(p));
    }

    @PostMapping("")
    public ResponseEntity updateUser(@RequestBody UserPojo p){
        return ResponseUtils.tryReturn("修改用户异常",()->userService.updateUserAndRole(p));
    }

    @DeleteMapping("")
    public ResponseEntity deleteUser(@RequestBody UserPojo p){
        return ResponseUtils.tryReturn("删除用户异常",()->userService.deleteUserRole(p));
    }

    @GetMapping("/userRole")
    public ResponseEntity userRole( UserPojo p){
        return ResponseUtils.tryReturn("查询用户-角色信息异常",()->userService.selectUserRole(p));
    }

    @GetMapping("/listPage")
    public ResponseEntity listPage(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   UserPojo userPojo, HttpServletRequest request){
        QueryWrapper<UserPojo> queryWrapper = QueryGenerator.initQueryWrapper(userPojo, request.getParameterMap());
        Page<UserPojo> page = new Page<>(pageNo, pageSize);
        return ResponseUtils.tryReturn("查询用户信息异常",()->userService.page(page, queryWrapper));
    }

    @PostMapping(value = "/login")
    public ResponseEntity login(@RequestBody UserPojo queryUser, HttpServletResponse response){
        //用户信息
        UserPojo user = userService.queryUserByAccount(queryUser);

        //账号不存在、密码错误
        if (user == null || !queryUser.getPassword().equals(user.getPassword())) {
            return ResponseEntity.status(500).body("账号或密码不正确");
        }

        //账号锁定
        if (Constants.ONE == user.getDelStats()) {
            return  ResponseEntity.status(500).body("该账号已被锁定");
        }
        // 过期时间
        Date date = new Date(System.currentTimeMillis() + jwtTokenUtil.getExpiration() * 60 * 1000L);

        // 生成token
        String token = jwtTokenUtil.generateToken(user.getUsername());
        logger.debug("生成token的userName :"+user.getUsername());
        logger.debug("token的获取userName :"+jwtTokenUtil.getUserName(token));
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expireTime", DateUtils.format(date, DateUtils.DATE_TIME_PATTERN));

        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        response.setHeader(jwtTokenUtil.tokenHeader(),token);
        user.setPassword(null);
        map.put("user",user);
        redis.setObject(redis.prefixKey(Constants.USER_PREFIX,user.getUsername()) ,user);
        return ResponseEntity.ok(map);
    }


    @GetMapping("/info")
    public ResponseEntity<?> getUserInfo(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>(2);
        String token =request.getHeader(jwtTokenUtil.tokenHeader());
        if(StringUtils.isEmpty(token)){
            return ResponseEntity.status(401).body("登录信息失效-Token为空");
        }else{
            String userAccount = jwtTokenUtil.getUserName(token);
            UserPojo user = redis.getObject(redis.prefixKey(Constants.USER_PREFIX,userAccount));
            if(user==null){
                return ResponseEntity.status(401).body("登录信息失效-获取不到用户信息,user:"+userAccount);
            }
            map.put("user",user);
            String str = redis.get(redis.prefixKey(Constants.MENU_PREFIX, token));

        }
        return ResponseEntity.ok(map);
    }

    @PostMapping("/logout")
    public  ResponseEntity<?> logout(HttpServletRequest request){

        String token = request.getHeader("Authorization");
        if(token!=null){
            String userName = jwtTokenUtil.getUserName(token);
            try {
                redis.del(userName);
                redis.del(redis.prefixKey(Constants.MENU_PREFIX,token));
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return ResponseEntity.ok("登出成功！");
    }



//    @GetMapping(value = "{id}")
//    public ResponseEntity<ResultEntity> queryUser(@PathVariable("id") String id){
//        UserPojo queryUser = new UserPojo();
//        queryUser.setUserCode(id);
//        UserPojo userPojo = userService.getOne(new QueryWrapper<>(queryUser));
//        ResultEntity re = new ResultEntity(ResultEntity.ResultEnum.success,userPojo);
//        return ResponseEntity.ok(re);
//    }
//
//    @GetMapping(value = "")
//    public ResponseEntity<ResultEntity> queryUserList(){
//        List<UserPojo> userList = userService.queryUserList();
//        ResultEntity re = new ResultEntity(ResultEntity.ResultEnum.success,userList);
//        return ResponseEntity.ok(re);
//    }

}
